import Datastore from 'nedb-promises'
import delete_unused_keys from './delete_unused_keys'

/**
 * 插入
 * @param db
 * @param newRecord
 * @param resJSON
 * @param callback
 */
const InsertData = (db: Datastore<{ _id: string; }>, newRecord: any, resJSON: ResponseDataType, callback: Function) => {
  db.find({ id: newRecord.id, _del: false }).then((res: any) => {
    if (res.length > 0) {
      resJSON.note = `id为 ${newRecord.id} 的记录已存在`
      callback && callback(resJSON)
      return
    } else {
      db.find({}).then((res: any) => {
        let dataLen = res.length
        db.insert({ ...newRecord, _del: false, id: String(dataLen + 1) }).then(async (res: any) => {
          res = delete_unused_keys([res])
          console.log('insert', res)
          resJSON = {
            code: 1,
            note: '提交成功',
            data: res,
            total: 1
          }
          callback && callback(resJSON)
        }).catch((error) => {
          resJSON.note = error
          callback && callback(resJSON)
        })
      })
    }
  }).catch((error) => {
    resJSON.note = error
    callback && callback(resJSON)
  })
}

/**
 * 同步插入
 * @param db
 * @param newRecord
 * @param resJSON
 * @returns
 */
const InsertDataSync = async (db: Datastore<{ _id: string; }>, newRecord: any, resJSON: ResponseDataType) => {
  await db.find({ id: newRecord.id, _del: false }).then(async (res: any) => {
    let dataLen = res.length
    if (dataLen > 0) {
      resJSON.note = `id为 ${newRecord.id} 的记录已存在`
    } else {
      await db.find({}).then(async (res: any) => {
        let dataLen = res.length
        await db.insert({ ...newRecord, _del: false, id: String(dataLen + 1) }).then(async (res: any) => {
          res = delete_unused_keys([res])
          console.log('insert', res)
          resJSON = {
            code: 1,
            note: '提交成功',
            data: res,
            total: 1
          }
        }).catch((error) => {
          resJSON.note = error
        })
      })
    }
  })
  return resJSON
}

export {
  InsertData,
  InsertDataSync,
}